package com.ganbo.demo.caffeine.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * caffeine配置
 *
 * @author: GanBo
 * @date: 2023/4/24 17:54
 */

@Configuration
@EnableCaching
public class CaffeineConfiguration {

    @Bean(name = "oneHourCacheManager")
    public CacheManager oneHourCacheManager() {
        Caffeine caffeine = Caffeine.newBuilder()
                .initialCapacity(6000)    //初始大小
                .maximumSize(6500)    //最大大小
//                .expireAfterWrite(3, TimeUnit.SECONDS); //写入/更新之后1小时过期
                .expireAfterAccess(3, TimeUnit.SECONDS); //写入/访问之后1小时过期

        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        caffeineCacheManager.setAllowNullValues(true);
        caffeineCacheManager.setCaffeine(caffeine);
        return caffeineCacheManager;
    }
}

